import axios from 'axios'
import { getToken } from '../api/user/index.ts'
import { ElMessage } from 'element-plus';
import router from '../router/index'
let isTokenExpiredMessageShown = false; // 标志是否已经显示了登录过期提示框

let request = axios.create({
    baseURL: 'http://localhost:3000/api',
    timeout: 30000,
})

// 添加请求相应拦截器
request.interceptors.request.use((config: { headers: { authorization: string; }; }) => {
    if (localStorage.getItem('FRONTEND_ACCESS_TOKEN')) {
        config.headers.authorization = 'token ' + localStorage.getItem('FRONTEND_ACCESS_TOKEN')
    }
    return config
})

request.interceptors.response.use((response: { data: any; }) => {
    return response.data
}, async (error: { response: { data: any; status?: any; config?: any; }; }) => {
    let { status, data, config } = error.response;
    if ((status == 401) && !config.url.includes("/token")) {
        const res = await getToken({ refreshToken: localStorage.getItem('FRONTEND_REFRESH_TOKEN') }); // 刷新Token
        if (res?.code === 200) {
            localStorage.setItem('FRONTEND_ACCESS_TOKEN', res.accessToken)
            return request(config);
        } else {
            localStorage.removeItem('FRONTEND_REFRESH_TOKEN')
            localStorage.removeItem('FRONTEND_ACCESS_TOKEN')
            if (!isTokenExpiredMessageShown) {
                isTokenExpiredMessageShown = true;
                ElMessage.error(error.response.data.data || '登录过期，请重新登录');
                router.push('/login')
            }
            return {};
        }
    } else if (status == 400) {
        ElMessage.error(error.response.data.data);
        return {};
    } else {
        if (error.response.data.msg) {
            ElMessage.error(error.response.data.data || '服务器内部错误');
        }
        if (status == 404) {
            router.push('/404')
        }
        return error.response;
    }

})

export default request
